package com.xishu.controller;

import com.xishu.entity.Company;
import com.xishu.entity.User;
import com.xishu.entity.plat.UserCompanyMapping;
import com.xishu.response.ResponseData;
import com.xishu.response.VerifyUtil;
import com.xishu.service.CommonService;
import com.xishu.service.CompanyService;
import com.xishu.service.MappingService;
import com.xishu.util.ServletUtil;
import com.xishu.util.Tools;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

@Api(description = "账号与公司绑定")
@RestController
public class UserCompanyMappingController implements Tools {

    @PostMapping(value = ("/user/company/mapping"), produces = ("application/json;charset=UTF-8"))
    @ApiOperation(value = "个人账号绑定公司")
    public ResponseData createOrModify(@RequestBody UserCompanyMapping userCompanyMapping) throws Exception {
        VerifyUtil.verify(() -> userCompanyMapping.getUserId() != null && userCompanyMapping.getCompanyId() != null);
        MappingService mappingService = MappingService.getInstance();
        mappingService.createUserCompanyMapping(userCompanyMapping.getUserId(), userCompanyMapping.getCompanyId());
        return ResponseData.emptyResponse();
    }

    @DeleteMapping(value = ("/user/company/mapping"), produces = ("application/json;charset=UTF-8"))
    @ApiOperation(value = "删除个人账号与公司的绑定关系")
    public ResponseData delete(@RequestBody UserCompanyMapping userCompanyMapping) throws Exception {
        return CommonService.getInstance().delete(userCompanyMapping);
    }

    @ApiOperation(value = "查询个人账号与公司的绑定关系")
    @PutMapping(value = ("/user/company/mapping"), produces = ("application/json;charset=UTF-8"))
    public ResponseData search(@RequestBody UserCompanyMapping reqUserCompanyMapping) throws Exception {
        User user = ServletUtil.getUser();
        //经理账号
        if (user != null && getBoolean(user.getShopManager()) && !getBoolean(user.getCompanyManager())) {
            UserCompanyMapping userCompanyMapping = new UserCompanyMapping();
            userCompanyMapping.setUserId(user.getId());
            userCompanyMapping.setUserName(user.getName());
            Long companyId = user.getCompanyId();
            userCompanyMapping.setCompanyId(companyId);
            Company company = CompanyService.getInstance().findCompanyById(companyId);
            userCompanyMapping.setCompanyName(company.getName());
            return CommonService.getInstance().createResponse(Arrays.asList(userCompanyMapping));
        }

        return CommonService.getInstance().searchResponse(reqUserCompanyMapping);
    }
}
